//
//  BaseCollectionViewController.m
//  MZBasic
//
//  Created by Sings on 2019/9/7.
//

#import "BaseCollectionViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "Masonry.h"
#import "BaseCollectCellModel.h"

@interface BaseCollectionViewController ()

@property (nonatomic, strong) BaseCollectionControllerModel *viewModel;

@property (nonatomic, strong, readwrite) BaseCollectionView *collectionView;

@property (nonatomic, strong) NSMutableDictionary *mdicCellRegister;

@property (nonatomic, strong) NSMutableDictionary *mdicHeaderRegister;

@property (nonatomic, strong) NSMutableDictionary *mdicFooterRegister;


@end

@implementation BaseCollectionViewController

@dynamic viewModel;


- (NSMutableDictionary *) mdicCellRegister {
    if (_mdicCellRegister == nil) {
        _mdicCellRegister = [NSMutableDictionary dictionary];
    }
    return _mdicCellRegister;
}

- (NSMutableDictionary *) mdicHeaderRegister {
    if (_mdicHeaderRegister == nil) {
        _mdicHeaderRegister = [NSMutableDictionary dictionary];
    }
    return _mdicHeaderRegister;
}

- (NSMutableDictionary *) mdicFooterRegister {
    if (_mdicFooterRegister == nil) {
        _mdicFooterRegister = [NSMutableDictionary dictionary];
    }
    return _mdicFooterRegister;
}

- (void)viewDidLoad {
    [super viewDidLoad];
 
    [self initCollectionView];
    [self initRefresh];
}

- (void) initCollectionView {
//    self.view.backgroundColor = [UIColor whiteColor];
    BZTHEME_COLOR(skin_content_bg_color,self.view,backgroundColor);
    CGFloat itemW1 = 117;
    CGFloat itemH1 = 44;
    UICollectionViewFlowLayout *flowLayout1 =[[UICollectionViewFlowLayout alloc]init];
    flowLayout1.itemSize=CGSizeMake(itemW1,itemH1);
    flowLayout1.sectionInset=UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout1.minimumLineSpacing = 0;
    flowLayout1.minimumInteritemSpacing = 0;
    [flowLayout1 setScrollDirection:UICollectionViewScrollDirectionVertical];
    BaseCollectionView *collectView = [[BaseCollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout1];
    collectView.showsVerticalScrollIndicator = NO;
//    collectView.backgroundColor = [UIColor whiteColor];
    BZTHEME_COLOR(skin_content_bg_color,collectView,backgroundColor);
    collectView.showsHorizontalScrollIndicator = NO;
    collectView.delegate = self;
    collectView.dataSource = self;
    [self.view addSubview:collectView];
    [collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    self.collectionView = collectView;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
    [self.collectionView addGestureRecognizer:longPress];
}

- (void) initRefresh {
    BaseWeakObj(self) if (self.viewModel.footerRefresh) {
        self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [weakself.viewModel refreshTableFooterEnd:^{
                if ([weakself.collectionView.mj_footer isRefreshing]) {
                    
                    [weakself.collectionView.mj_footer endRefreshing];
                }
            }];
        }];
    }
    
    if (self.viewModel.headerRefresh) {
        self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakself.viewModel refreshTableHeaderEnd:^{
                if ([weakself.collectionView.mj_header isRefreshing]) {
                    
                    [weakself.collectionView.mj_header endRefreshing];
                }
            }];
        }];
    }
}

#pragma mark collection代理
- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.viewModel.sectionArray.count;
}

- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    BaseTableSectionModel *sectionModel = self.viewModel.sectionArray[section];
    __weak typeof(self) weakSelf = self;
    sectionModel.sectionRefresh = ^(UITableViewRowAnimation animation) {
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:section];
        [weakSelf.collectionView reloadSections:indexSet];
    };
    sectionModel.tableRefresh = ^(UITableViewRowAnimation animation) {
        [weakSelf.collectionView reloadData];
    };
    return self.viewModel.sectionArray[section].rowArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    BaseViewModel *viewModel = self.viewModel.sectionArray[indexPath.section].rowArray[indexPath.row];
    Class cellCass = [[MZRouting sharedInstance] getCollectCellClassWithViewModel:viewModel];
    if (self.mdicCellRegister[NSStringFromClass(cellCass)] == nil) {
        NSString *identifier = [cellCass collectionCellReuseIdentifier];
        [self.collectionView registerClass:cellCass forCellWithReuseIdentifier:identifier];
        self.mdicCellRegister[NSStringFromClass(cellCass)] = @"1";
    }
    BaseCollectionViewCell *cell = [cellCass baseCollectionViewCellWithCollectionView:(BaseCollectionView *)collectionView WithIndexPath:indexPath];
    cell.viewModel = viewModel;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        BaseViewModel *viewModel = self.viewModel.sectionArray[indexPath.section].sectionHeaderView;
        
        Class headerCass = [[MZRouting sharedInstance] getCollectionHeaderFooterWithViewModel:viewModel];
        if (self.mdicHeaderRegister[NSStringFromClass(headerCass)] == nil) {
            NSString *identifier = [headerCass CollectionHeaderFooterReuseIdentifier];
            [self.collectionView registerClass:headerCass forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:identifier];
            self.mdicHeaderRegister[NSStringFromClass(headerCass)] = @"1";
        }
        
        BaseCollectionHeaderFooterView *headerView = [headerCass baseCollectionHeaderFooterViewWithCollectionView:(BaseCollectionView *)collectionView AndKind:UICollectionElementKindSectionHeader AndIndexPath:indexPath];
        headerView.viewModel = viewModel;
        return headerView ;
        
    }else if (kind == UICollectionElementKindSectionFooter) {

        BaseViewModel *viewModel = self.viewModel.sectionArray[indexPath.section].sectionFooterView;
        
        Class footerCass = [[MZRouting sharedInstance] getCollectionHeaderFooterWithViewModel:viewModel];
        if (self.mdicHeaderRegister[NSStringFromClass(footerCass)] == nil) {
            NSString *identifier = [footerCass CollectionHeaderFooterReuseIdentifier];
            [self.collectionView registerClass:footerCass forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:identifier];
            self.mdicHeaderRegister[NSStringFromClass(footerCass)] = @"1";
        }
        
        BaseCollectionHeaderFooterView *footerView = [footerCass baseCollectionHeaderFooterViewWithCollectionView:(BaseCollectionView *)collectionView AndKind:UICollectionElementKindSectionFooter AndIndexPath:indexPath];
        footerView.viewModel = viewModel;
        return footerView ;
    }else {
        return nil;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    BaseViewModel *viewModel = self.viewModel.sectionArray[section].sectionHeaderView;
    return CGSizeMake(viewModel.width, viewModel.height);
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    BaseViewModel *viewModel = self.viewModel.sectionArray[section].sectionFooterView;
    return CGSizeMake(viewModel.width, viewModel.height);
}

- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    BaseViewModel *viewModel = self.viewModel.sectionArray[indexPath.section].rowArray[indexPath.row];
    return CGSizeMake(viewModel.width, viewModel.height);
}

- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    BaseCellModel *viewModel = self.viewModel.sectionArray[indexPath.section].rowArray[indexPath.row];
    if (viewModel.cellClick) {
        viewModel.cellClick(indexPath);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    BaseCollectionSectionViewModel *viewModel = self.viewModel.sectionArray[section];
    return UIEdgeInsetsMake(viewModel.locationInsets.edgeTop,viewModel.locationInsets.edgeLeft,viewModel.locationInsets.edgeBottom,viewModel.locationInsets.edgeRight);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    BaseCollectionSectionViewModel *viewModel = self.viewModel.sectionArray[section];
    return viewModel.locationInsets.miniLine;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    BaseCollectionSectionViewModel *viewModel = self.viewModel.sectionArray[section];
    return viewModel.locationInsets.miniInter;
}

// 拖动排序
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longPress
{
  switch (longPress.state) {
    case UIGestureRecognizerStateBegan:
    { //手势开始
      //判断手势落点位置是否在row上
      NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
      if (indexPath == nil) {
        break;
      }
      BaseCellModel *viewModel = self.viewModel.sectionArray[indexPath.section].rowArray[indexPath.row];
      if (!viewModel.isMove) {
        break;
      }
      UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
      [self.view bringSubviewToFront:cell];
      //iOS9方法 移动cell
        if (@available(iOS 9.0, *)) {
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        } else {
            // Fallback on earlier versions
        }
    }
      break;
    case UIGestureRecognizerStateChanged:
    { // 手势改变
      // iOS9方法 移动过程中随时更新cell位置
        NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longPress locationInView:self.collectionView]];
        if (indexPath != nil) {
          BaseCellModel *viewModel = self.viewModel.sectionArray[indexPath.section].rowArray[indexPath.row];
          if (!viewModel.isMove) {
              break;
          }
        }
        
        if (@available(iOS 9.0, *)) {
            [self.collectionView updateInteractiveMovementTargetPosition:[longPress locationInView:self.collectionView]];
        } else {
            // Fallback on earlier versions
        }
    }
      break;
    case UIGestureRecognizerStateEnded:
    { // 手势结束
      // iOS9方法 移动结束后关闭cell移动
        if (@available(iOS 9.0, *)) {
            [self.collectionView endInteractiveMovement];
        } else {
            // Fallback on earlier versions
        }
    }
      break;
    default: //手势其他状态
          if (@available(iOS 9.0, *)) {
              [self.collectionView cancelInteractiveMovement];
          } else {
              // Fallback on earlier versions
          }
      break;
  }
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
    BaseCellModel *viewModel = self.viewModel.sectionArray[indexPath.section].rowArray[indexPath.row];
    return viewModel.isMove;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    [self.viewModel oldPath:sourceIndexPath MoveToPath:destinationIndexPath];
}


- (void) refreshView {
    [self.collectionView reloadData];
}

@end
